import {
  reqGetCode,
  reqUserRegister,
  reqUserLogin,
  reqUserInfo,
  reqLogout,
} from "../../api/index";
import { setToken, getToken, removeToken } from "../../utils/token";

const state = {
  code: "",
  token: getToken(),
  userInfo: {},
};
const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone);
    if (result.status == 200) {
      commit("GETCODE", result.data.data);
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  // 注册
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user);
    if (result.data.code == 200) {
      return "ok";
    } else {
      alert(result.data.message);
    }
  },
  // 登录
  async userLogin({ commit }, data) {
    let result = await reqUserLogin(data);
    if (result.data.code == 200) {
      commit("USERLOGIN", result.data.data);
      setToken(result.data.data.token);
      return "ok";
    } else {
      alert(result.data.message);
    }
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqUserInfo();
    if (result.status == 200) {
      commit("GETUSERINFO", result.data.data);
    }
  },
  // 退出登录
  async userLogout({ commit }) {
    let result = await reqLogout();
    if (result.data.code == 200) {
      commit("USERLOGOUT");
      return "ok";
    }
  },
};
const mutations = {
  GETCODE(state, code) {
    state.code = code;
  },
  USERLOGIN(state, userList) {
    state.token = userList.token;
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  // 清除本地存储
  USERLOGOUT(state) {
    //   将仓库中的用户相关信息清空
    state.token = "";
    state.userInfo = {};
    removeToken();
  },
};
const getters = {
  //   userName(state) {
  //     return state.userInfo.name || "";
  //   },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
